<?php
/*
 * object(stdClass)#3 (2) { ["alipay_system_oauth_token_response"]=> object(stdClass)#4 (6) { ["access_token"]=> string(40) "composeBa59bdf8e223d4faa82ef48ce67f75X62" ["alipay_user_id"]=> string(32) "20880047227871702781910743017362" ["expires_in"]=> int(3600) ["re_expires_in"]=> int(3600) ["refresh_token"]=> string(40) "composeB03d46fe19a264814b0715bba01510X62" ["user_id"]=> string(16) "2088012954780622" } ["sign"]=> string(344) "X+TrXJh8GOGIS7PbkyMaucb/HYVC6w+DY+NihjNtwmhoLB3jAe8rXFQJ3LQZ5HEUQFGpK8D9hAD/CuHunq8jCdZEGApsj+tQNOk7caLF2kM+V/Qw0orxdV8L1fq76si4/szG9aXUVvCvurWaICLK9W2ouSnJ2PVQpmWusAOkxEZMyq3ucRjEgcGBNsqEifCtDfDGsvcxWtz64EMoZR6HFhT3gQgqMH0fQ9vYNMdaUcAQ14Gyk3t60Qd4HZTpHjio1oLde2c8EyrkSsvh/q3OsxjOqvES2MDVs5wxLGLyY/+vjhd3d0WP7jotOVc1EwP5/QU6Juv0j2VIoCCS33bwEA==" } string(40) "composeBa59bdf8e223d4faa82ef48ce67f75X62" string(32) "20880047227871702781910743017362" string(16) "2088012954780622"
 *
 * */
//namespace Card;
include '../AopClient.php';
include '../SignData.php';
include('../AlipayMobilePublicMultiMediaClient.php');
include('../request/AlipayMarketingCardQueryRequest.php');
include('../request/AlipayMarketingCardFormtemplateSetRequest.php');
include('../request/AlipayMarketingCardTemplateQueryRequest.php');
include('../request/AlipayMarketingCardTemplateCreateRequest.php');
include('../request/AlipayMarketingCardActivateurlApplyRequest.php');
include('../request/AlipaySystemOauthTokenRequest.php');
include('../request/AlipayMarketingCardOpenRequest.php');
function getconfig($key){
    $source=include('./config.php');
    return $source[$key];
}
function conventjson($data){
    return json_encode(json_encode($data,JSON_UNESCAPED_UNICODE));
}
//$token=get_token1('f7266103749e4375af7bc71b8d4aSX62');die;
class Card{
    private	$format = 'json';
    private	$aop;

    function __construct(){
        header("Content-type:text/html;charset=utf-8");
        $this->aop = new \AopClient ();
        $this->aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $this->aop->appId = '2018011901971979';
        $this->aop->rsaPrivateKey = 'MIIEpAIBAAKCAQEA0Hx+9wgN4ParmGATI2ykd4HnwqV2yhUKfPXCLWMXCxyT83akGBPt/svUBeYCd5ZhVMMebYQ6ZfJVtfCCF6aQAQQvZujgcCdWm4nO6W1w7ryIhuwvT1ocsBKBGl3g+9YfvHWfPx2otIpvL5xPBYz3+0bk0Ge5EuVT4xjNsfIfNVMhOCddtX0VOfNFE7gzu6uVsEatFXLcwq2qCTVrx4SWjLCpYVmTdtoFAgJqrSvuXHDccAj7lA44vy1xJRpfzhddE+uQ2G+wcoK6Z/CW6RDpJ1zLhfcSRfvxO+gWLk72UI7W6U3LAa5ULc3moUqFbOfjE73fjQIynCIoAT1AdRq7WwIDAQABAoIBAQCBiQid1dxBrSFakD7z4JmjQwxLbOEMl9wnXc6iwpFbrwrh1xIHf8J8cAoxDAL2aHHa50xtgR2Dn/jPDTrXFP8eEoqdJw3jwR1XkF0FvaDQREWThwWyCOwQHb8nMbMK5bRcNLyXy4a5fdWtQDH84eRltFuQfRGJgwEG9a8/446uYvP5ZuW5DDyGWKJ6XbQbaYfsZ7ID5ek4/I9xZYUeMRe8xyeGB2Es4Gq0Cz0q2uGicUOB2d28nPNnK9gzSrJIo3EZu9nJg+T83YSMeO5f0T3YW1Id2nvL4Ksbp6Gx23jLbGCIKcDKzJLgt/yJBEokYHaTzU1VN98yBbTor27XSik5AoGBAOvQ4LCNpOwJLVpX+JC/7yFz24XfnYy8gqwN4fVdOPV9tnUXGyfgxiAPsOTwSh29oRWEKoa6pTH8iG4RBLcvy4jx6I4WsKJYYTxyq1xbZrJwXNRf/QKDDhAnXsYzeY6nWxEnbAFua2b4fnGT61iOXo8Aibc6vqP7a+Hd//epAoiHAoGBAOJUx9Ku25cKGc/H81NITSjclp5obNWpOPC0MfspGrKrT3Q3CaVeTVW9EwQMlpgi0F5K42G6PccxGWNgHSSSED3/lz3/MOpmVqvL7jFM7h8kInv8LvMvTsfcbtK4lItSSJOQnYYGOrYmtnyiYxwkRjPXBoG+hkwX3RpVbr2mJW+NAoGANL0tUy8KgGN5Cih8hdr3HzMrGGCveqc6TkJ4k4h60aSA5uT5BM0nYkpAFKOM3+PmH8rEPAeIJIrG9F7IADQnQARiL0zxyg0cCgnXOzuR1zx79l9VVXd78K7takRe3kGdg1Oeux830/qlRL+BNff5O+Ax7JGtyzzSntwof/oDgAcCgYAc+YmTWTtXfL2NMiXedZUbNBI8OVYljEJz3j2/z6VRVkkXsawUdZwk682xaQMmet5+E8xESJl8FLcRV86jTeeyaDQuhar3dx6FY9gci6K4beHUSZahH19QitHNPEAYDfKooYzpCYceppoaHpfdlG9AV7jHh2Kd/zgZFPLWaJzGSQKBgQC0dJs5fN284JQpZtIlfcZEaqCF/YBodi8DLhvPd4QWIAivmD5x24ctF/YKOqAdcb7/kmnLcHSn26CpKujmg/sjGUzw4l+FEm8/BH6IcggA6LRYBfc51O5LhWo/mlXhP5HgHFBynnHdIFT8x2v+N0lI3lCMHmxFSC8MDFvBe8r9Kw==';
        $this->aop->alipayrsaPublicKey='MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnnlOO815QsoDpUhenK49IWUwlpwQ18MPjRLbb+FjDMdiF8357i6W0aXo1WuYa1nvTREm9KkhfLn90au5oAyvGSTFOlDdrtNajpNZn0NWsUmnbq0pf1xLX+5vGkbzvjQR/B699xES6SpuYCwOrSkkQSUvvsZ+3Iv+cVUABQM3uTbieqe1yjF9T2YAFh09w/mvMpRFzYb/FlfUl72ewOr7FCRn3mBu5PYDNkrTQiNiECOXj1bO6/O6rFZ8lqvOV7Tb0hk8iobT19dMhlUCR4jE1jWGTTHVHZh1OrlV1zHjkHcRdLihCyMM3WQWz5pOvDuBhtl9JVA/MaeeFEgHTxde3QIDAQAB';
        $this->aop->apiVersion = '1.0';
        $this->aop->signType = 'RSA2';
        $this->aop->postCharset='utf-8';
        $this->aop->format='json';
    }

    public function createTemplate($data){
        $request = new \AlipayMarketingCardTemplateCreateRequest ();
        $request->setBizContent($data);
        $result = $this->aop->execute ( $request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        var_dump($result);
        if(!empty($resultCode)&&$resultCode == 10000){
            echo "成功";
        } else {
            echo "失败";
        }

    }
    public function addMarketCardJson(){
        $json_data = array();
        $json_data['request_id'] = date('YmdHis').mt_rand(10000,99999);
        $json_data['card_type'] = 'OUT_MEMBER_CARD';
        $json_data['biz_no_prefix'] = 'prex';
        $json_data['biz_no_suffix_len'] = '10';
        $json_data['write_off_type'] = 'qrcode'; #qrcode: 二维码 dqrcode: 动态二维码 barcode: 条码 dbarcode: 动态条码 text: 文本
        $json_data['template_style_info']['card_show_name'] = '星辰会员卡';
        $json_data['template_style_info']['logo_id'] = 'YS6zsqoES5iHcD4uGwrP6QAAACMAAQED';  # logo 上传后的ID 1M以内，格式bmp、png、jpeg、jpg、gif； 尺寸不小于500*500px的正方形； 请优先使用商家LOGO；
        $json_data['template_style_info']['color'] = 'red'; #卡片背景色
        $json_data['template_style_info']['background_id'] = '1BPt1AVNQnGAkntb2PFw3QAAACMAAQED'; # 上传背景图片返回的ID
        $json_data['template_style_info']['bg_color'] = 'rgb(153,204,153)'; # 背景色
        #$json_data['template_style_info']['feature_descriptions'] = array('使用高端会员卡，0门卡享受9折优惠') ; # √ 描述
        #$json_data['template_style_info']['slogan'] = '会员权益享不停'; # √ 标语
        #$json_data['template_style_info']['slogan_img_id'] = '1BPt1AVNQnGAkntb2PFw3QAAACMAAQED'; # √ 标语图片ID
        #$json_data['template_style_info']['brand_name'] = '高端会员'; # √ 品牌名称

        $json_data['template_benefit_info'] = array( # √ 权益信息， 1、在卡包的卡详情页面会自动添加权益栏位，展现会员卡特权， 2、如果添加门店渠道，则可在门店页展现会员卡的权益
            array(
                'title' => '消费即折扣1', #  权益标题
                'benefit_desc' => ['消费即折扣2'], #  权益描述
                'start_date' => '2016-07-18 15:17:23', #  权益开始时间
                'end_date' => '2017-07-18 15:17:23', #  权益结束时间
            )
        );

        $json_data['column_info_list'] = array(
            array(
                'code' => 'BENEFIT_INFO', #  code 唯一码 写死
                'more_info' => array(
                    'title'  => '会员专享权益', #  二级页面标题√
                    'url'    => 'BASE_DOMAIN', #  超链接(选择openweb的时候必须填写url参数内容)√
                    'params' => '{}', #  需要URL地址回带的值，JSON格式(openweb时填)√
                    #    'descs'  => ['会员生日打六折'] #  选择opennative的时候必须填写descs的内容√
                ),
                'title' => '进入店铺', #  栏目标题
                'operate_type' => 'openWeb', # 1、openNative：打开二级页面，展现 more中descs 2、openWeb：打开URL 3、staticinfo：静态信息
//                'value' => '80' , #  卡包详情页面，卡栏位右边展现的值√
            )
        );

        $json_data['field_rule_list'] = array(
            array(
                'field_name' => 'Balance',  # Balance：金额 Point：整数 Level：任意字符串 OpenDate：开卡日期 ValidDate：过期日期
                'rule_name'  => 'ASSIGN_FROM_REQUEST', # 1.ASSIGN_FROM_REQUEST: 以rule_value为key值，表示该栏位的值从会员卡开卡接口中获取，会员卡开卡接口的card_info中获取对应参数值
                # 2、DATE_IN_FUTURE: 生成一个未来的日期（格式YYYY-MM-DD)，当选择DATE_IN_FUTURE的时候，field_name 必须是OpenDate或ValidDate， 值为(10m或10d 分别表示10个月或10天)
                # 3、CONST: 常量，会员卡开卡接口进行开卡的时候使用模板创建时候设置的值，即取rule_value的值
                'rule_value' => 'Balance'  # 根据rule_name，采取相应取值策略
                # 3.CONST：直接取rule_value作为卡属性值
                # 3.DATE_IN_FUTURE：10m或10d 分别表示10个月或10天
                # 1.ASSIGN_FROM_REQUEST：在开卡Reuqest请求中按rule_value取值，现在和field_name对应的为（OpenDate、ValidDate、Level、Point、Balance）
            ),
            /*  array(
                            'field_name' => 'Point',
                            'rule_name'  => 'ASSIGN_FROM_REQUEST',
                            'rule_value' => 'Point'
                        ),
                        array(
                            'field_name' => 'Level',
                            'rule_name'  => 'CONST',
                            'rule_value' => '1'
                        ),
                        array(
                            'field_name' => 'OpenDate',
                            'rule_name'  => 'DATE_IN_FUTURE',
                            'rule_value' => '0d'
                        ),
                        array(
                            'field_name' => 'ValidDate',
                            'rule_name'  => 'DATE_IN_FUTURE',
                            'rule_value' => '12m'
                        )*/
        );
//        $json_data['open_card_conf'] = array( # √
//            'open_card_source_type' => 'ISV', #ISV：外部系统 MER：直连商户
//            'source_app_id' => '2016101702200000',  # 渠道APPID，提供领卡页面的服务提供方
//            'open_card_url' => BASE_DOMAIN, # 开卡连接，必须http、https开头
//            #'conf' => '' ,  # √ 配置，预留字段，暂时不用
//        );

//        $json_data['service_label_list'] = ['HUABEI_FUWU'] ; # √ 服务Code HUABEI_FUWU：花呗服务（只有需要花呗服务时，才需要加入该标识）
//        $json_data['shop_ids'] = []; # √ 会员卡上架门店id（支付宝门店id），既发放会员卡的商家门店id

//        $json_data['pub_channels'] = array( # √ 卡模板投放渠道
//            array(
//                'pub_channel' => 'SHOP_DETAIL' , # 1、SHOP_DETAIL:店铺详情页 2、PAYMENT_RESULT: 支付成功页（支付成功页暂不支持）
//                'ext_info'    => '{}'   # 扩展信息，无需配置 "key":"value"
//            )
//        );

#card_level_conf 这个参数 有问题 请勿添加
//        $json_data['card_level_conf'] = array( # √ 卡级别配置
//            array(
//                'level' => 'VIP3', # 会员级别 该级别和开卡接口中的levle要一致
//                'level_show_name' => '黄金会员', # 会员级别显示名称
//                'level_icon' => 'aPQKWaYXQZimxEFz09nTBQAAACMAAQED',# 会员级别对应icon， 通过接口（alipay.offline.material.image.upload）上传图片
//                'level_desc' => '黄金会员享受免费停车，加油85折', # 会员级别描述
//            ),
//            array(
////                'level' => 'VIP2',
////                'level_show_name' => '银牌会员',
////                'level_icon' => 'rIBh_U4IRfmJtP97b-M5QQAAACMAAQED',
////                'level_desc' => '银牌会员享受免费停车，加油9折',
//                 ),
//            array(
////                'level' => 'VIP1',
////                'level_show_name' => '铁牌会员',
////                'level_icon' => 'U1GnhAh8QNGJxkBcBADyQAAAACMAAQED',
////                'level_desc' => '铁牌会员享受免费停车,加油9折',
//                 )
//        );
        return $json_data;
    }
    //会员卡开卡表单模板配置
    public function setformtemplate($template_id){
        $request = new \AlipayMarketingCardFormtemplateSetRequest ();
        $post_data=[
            'template_id'=>$template_id,
            'fields'=>[
                'required'=>['common_fields'=>['OPEN_FORM_FIELD_MOBILE']],                                                       'optional'=>['common_fields'=>['OPEN_FORM_FIELD_GENDER','OPEN_FORM_FIELD_IDCARD']]
            ]
        ];
        $request->setBizContent(json_encode($post_data,JSON_UNESCAPED_UNICODE));
        $result = $this->aop->execute ( $request);

        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        var_dump($result);
        if(!empty($resultCode)&&$resultCode == 10000){
            echo "成功";
        } else {
            echo "失败";
        }
    }
    public function activateurl_apply($template_id){
        $request = new \AlipayMarketingCardActivateurlApplyRequest ();
        $post_data=[

            'template_id'=>$template_id,
            'callback'=>'http://180.76.59.168/kabao/aop/test/token.php',
        ];
        $request->setBizContent(json_encode($post_data,JSON_UNESCAPED_UNICODE));
        $result = $this->aop->execute ( $request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        var_dump( urldecode($result->alipay_marketing_card_activateurl_apply_response->apply_card_url));
//https%3A%2F%2Fmemberprod.alipay.com%2Faccount%2Fopenform%2Factivecard.htm%3Fapp_id%3D2017122101047175%26template_id%3D20180118000000000763343000300730%26__webview_options__%3DcanPullDown%253dNO%2526transparentTitle%253dauto%26out_string%3Dxiaobai%26callback%3Dhttp%3A%2F%2Fitblw.com
        if(!empty($resultCode)&&$resultCode == 10000){
            echo "成功";
        } else {
            echo "失败";
        }
    }
    public function get_token($code){
        $request = new AlipaySystemOauthTokenRequest ();
        $request->setGrantType("authorization_code");
        $request->setCode($code);
        $result = $this->aop->execute ( $request);
        var_dump($result);
        return     $result->alipay_system_oauth_token_response->access_token;
    }
    public function card_open($template_id,$token){
        $request = new \AlipayMarketingCardOpenRequest ();
        $post_data=[
            'out_serial_no'=>'E201611250222479XsXX1',
            'card_template_id'=>$template_id,
            'card_user_info'=>[
                'user_uni_id'=>'2088012954780622',
                'user_uni_id_type'=>'UID',
            ],
            'card_ext_info'=>[
                'biz_card_no' => 'hha',#支付宝业务卡号 说明： 1、开卡成功后返回该参数，需要保存留用； 2、开卡/更新/删卡/查询卡接口请求中不需要传该参数；
                'external_card_no'=>'11111', # 商户外部会员卡卡号 说明： 1、会员卡开卡接口，如果卡类型为外部会员卡，请求中则必须提供该参数； 2、更新、查询、删除等接口，请求中则不需要提供该参数值；
                'open_date' => date('Y-m-d H:i:s'),
                'valid_date' => date('2022-m-d H:i:s'),
                'level' =>'VIP1',
                'point' => '88',
                'balance' => '128.88'
            ],
        ];
        $request->setBizContent(json_encode($post_data,JSON_UNESCAPED_UNICODE));

        $result = $this->aop->execute ( $request,$token  );

        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        if(!empty($resultCode)&&$resultCode == 10000){
            echo "成功";
        } else {
            echo "失败";
        }
    }
}

$ne=new Card();

$code='b4f21c33a6b24a17b3127e4be9f4UC62';
$ne->card_open('20180122000000000774265000300735','composeBa59bdf8e223d4faa82ef48ce67f75X62');